package ru.amse.tsyganov.jumleditor.graphicaleditor;

import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.model.State;
import ru.amse.tsyganov.jumleditor.view.activepoints.ActivePoint;
import ru.amse.tsyganov.jumleditor.view.activepoints.TransitionActivePoint;
import ru.amse.tsyganov.jumleditor.view.repr.StateView;

/*package*/ class TrackingActivePointMode extends EditorMode {
	
	private final GraphicalEditor graphicalEditor;
	
	private final ActivePoint activePoint;
	
	public TrackingActivePointMode(ActivePoint activePoint, 
			GraphicalEditor graphicalEditor) {
		
		if (activePoint == null || graphicalEditor == null) {
			throw new IllegalArgumentException();
		}
		
		this.activePoint = activePoint;
		this.graphicalEditor = graphicalEditor;	
	}
	
	@Override
	public void initState() {
		if (activePoint instanceof TransitionActivePoint) {
			TransitionActivePoint p = (TransitionActivePoint) activePoint;
			
			StateView<? extends State> s;
			if (p.isSourceMoving()) {
				s =	graphicalEditor.getActivityGraphView().getModelViewMap().
					getStatesMap().get(p.getTransitionView().getModel().getTarget().getContainer());
			} else {
				s =	graphicalEditor.getActivityGraphView().getModelViewMap().
					getStatesMap().get(p.getTransitionView().getModel().getSource().getContainer());
			}
			
			graphicalEditor.getActivityGraphView().setExcludedState(s);
			graphicalEditor.getActivityGraphView().setPaintConnectionPoints(true);
		}
		
		graphicalEditor.getCanvas().setCursor(
				activePoint.getCursor());
	}

	@Override
	public void keyPressed(KeyEvent e) {
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	@Override
	public void mouseDoubleClick(MouseEvent e) {
	}

	@Override
	public void mouseDown(MouseEvent e) {
	}

	@Override
	public void mouseMove(MouseEvent e) {
		activePoint.move(e.x, e.y);
	}

	@Override
	public void mouseUp(MouseEvent e) {
		Command c = activePoint.createCommandForAction();
		if (c != null) {
			graphicalEditor.getViewsManager().executeCommand(c);
		}
		graphicalEditor.getCanvas().redraw();
		graphicalEditor.getCanvas().update();
		graphicalEditor.setEditorMode(graphicalEditor.getSelectionMode());
		
		graphicalEditor.getActivityGraphView().setExcludedState(null);
		graphicalEditor.getActivityGraphView().setPaintConnectionPoints(false);
	}

	@Override
	public void paintControl(PaintEvent e, Coordinates coordinates) {
		activePoint.paintTempResult(e.gc, coordinates);
	}
}
